//index.js

import { bleHelper } from "../../utils/bleHelper/bleHelper"
import { bleLockHelper } from "../../utils/bleHelper/bleLockHelper"
import { hex_md5 } from "../../utils/md5"

//获取应用实例
const app = getApp()

Page({
  data: {
    secretKey: null,
    _clearCount: 0,
    _chipKey: null,
    _mcuSuccess: false,
    _setChipKeySuccess: false
  },
  onLoad: function () {
    bleLockHelper.deviceId = "5D:69:55:44:33:88"

  },
  bindLock() {
    var that = this
    var inputPwd = "123456"
    var hexMd5 = hex_md5(inputPwd)
    var hexMd51 = hex_md5(hexMd5)
    //lockPwd,这就是真正的锁密钥了
    var lockPwd = hexMd51.substr(0, 24)
    this.data._chipKey = lockPwd

    // bleLockHelper.lockInfoCallback = res => {
    //   if (res.success) {
    //     that.data._mac = res.data
    //     that._checkAllSuccess()
    //   }
    // }
    wx.showLoading({
      title: '绑定中',
    })


    bleLockHelper.chipCallback = res => {
      if (res.success) {
        //真正的锁密钥,不用存的哈，没有服务端，自己存一下免得手动写代码
        this.data._setChipKeySuccess = true
        // wx.setStorage({
        //   data: lockPwd,
        //   key: 'initLockChipKey' + that.data._housingId,
        // })
        // wx.setStorage({
        //   key: 'initDeviceId' + that.data._housingId,
        //   data: that.data._deviceId,
        // })
        bleLockHelper.secretKey = lockPwd
        wx.hideLoading()

        wx.showToast({
          title: '绑定成功'
        })
        // that._checkAllSuccess()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '初始化锁失败，已被他人绑定',
          icon: 'none'
        })
        // that._setKey()
      }
    }

    /**
     * mcu
     */
    bleLockHelper.getMcuCallback = res => {
      if (res.success) {
        // clearTimeout(that.data._readMcuIdTimeout)
        that.data._mcuSuccess = true
        // that.data._mcuId = res.data
        //获取mcuId成功后，添加一个密码,且为管理员
        setTimeout(() => {
          bleLockHelper.blueSendAddPwd(0x0b, 0, inputPwd)
        }, 50);
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '初始化锁失败，请重试',
          icon: 'none'
        })
        // that._setKey()
      }
    }

    /**
     * 添加管理员账号
     * 添加成功后，且获取mcu成功后，传参给后台
     */
    bleLockHelper.setUserCallback = res => {
      if (res.success) {
        //添加管理员成功
        that.data._userSuccess = true
        that.data._userPwdId = res.data
        setTimeout(() => {
          bleLockHelper.blueSendChipkey(lockPwd)
        }, 50);
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '添加管理员失败，请重试',
          icon: 'none'
        })
        // that._setKey()
      }
    }

    bleLockHelper.sendCallback = res => {
      //发送失败
      if (!res.success) {
        console.log("ble", "send fail cmd:" + res.cmd)
        wx.hideLoading()
        switch (res.cmd) {
          case bleLockHelper.data.LS_COMM_USER_VALID:
            wx.showToast({
              title: '初始化锁失败，请重试',
              icon: 'none'
            })
            // that._setKey()
            break;
          case bleLockHelper.data.LS_COMM_MAX_GET_MCUID:
            wx.showToast({
              title: '初始化锁失败，请重试',
              icon: 'none'
            })
            // that._setKey()
            break;
          case bleLockHelper.data.LS_COMM_CHIPKEY:
            wx.showToast({
              title: '初始化锁失败，请重试',
              icon: 'none'
            })
            // that._setKey()
            break;
        }
      }
    }
    bleHelper.initBle(res => {
      //1.获取mucId  2.添加管理员， 3.设置密钥
      if (!that.data._mcuSuccess) {
        //修改密码成功后，获取mcuId
        bleLockHelper.blueSendMCUID()
        // that.data._readMcuIdTimeout = setTimeout(() => {
        //   wx.hideLoading()
        //   wx.showToast({
        //     title: '初始化锁失败，请重试',
        //     icon: 'none'
        //   })
        // }, 10000);
      } else if (!that.data._userSuccess) {
        //获取mcu成功后，添加一个密码,且为管理员
        bleLockHelper.blueSendAddPwd(0x0b, 0, inputPwd)
      } else if (!this.data._setChipKeySuccess) {
        //修改密钥，很重要
        bleLockHelper.blueSendChipkey(lockPwd)
      }
    }, err => {
      wx.hideLoading()
      wx.showToast({
        title: err,
      })
    })
  },

  unbindLock() {
    var that = this

    wx.showLoading({
      title: '删除门锁中',
      icon: 'none',
      mask: true
    })
    bleLockHelper.clearUserCallback = res => {
      if (res.success) {
        that.data._clearCount++
        if (that.data._clearCount >= 2) {
          setTimeout(() => {
            bleLockHelper.blueSendChipkey(defaultKey)
          }, 50);
        } else
          if (that.data._clearCount == 1) {
            //再清所有用户
            setTimeout(() => {
              bleLockHelper.blueSendClearData(1)
            }, 50);
          }
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '删除锁失败,请重试',
        })
      }
    }
    bleLockHelper.chipCallback = res => {
      if (res.success) {
        //清空成功
        bleHelper.releaseBle()
        //保存已删除锁
        wx.setStorage({
          data: "true",
          key: 'deletedLock' + wx.getStorageSync('housingId'),
        })
        bleLockHelper.secretKey = defaultKey
        that._requestDeleteLock()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '恢复出厂失败，请重试',
        })
      }
    }

    //LS_COMM_CLEAR
    bleLockHelper.sendCallback = res => {
      if (!res.success) {
        switch (res.cmd) {
          case bleLockHelper.data.LS_COMM_CHIPKEY:
            wx.hideLoading()
            wx.showToast({
              title: '恢复出厂失败，请重试',
            })
            break;
          case bleLockHelper.data.LS_COMM_CLEAR:
            wx.hideLoading()
            wx.showToast({
              title: '恢复出厂失败，请重试',
            })
            break;
        }
      }
    }

    //保存已删除锁
    this.data._clearCount = 0
    bleHelper.initBle(res => {
      //先清日志
      bleLockHelper.blueSendClearData(2)
    }, res => {
      wx.hideLoading()
      wx.showToast({
        title: res,
        icon: 'none'
      })
    })
  },
  addUser() {
    var that = this
    wx.showLoading({
      title: '正在添加密码',
      icon: 'none', mask: true
    })
    var addSuccess = false
    bleLockHelper.setUserCallback = res => {
      wx.hideLoading()

      if (res.success) {
        if (!addSuccess) {
          addSuccess = true
          //添加密码成功，发送数据到服务端
          // that._sendAddPwdToServer(pwd, res.data)
        }
      } else {
        wx.showToast({
          title: '添加密码失败，请重试',
          icon: 'none'
        })
      }
    }
    bleLockHelper.sendCallback = res => {
      if (res.cmd == bleLockHelper.data.LS_COMM_USER_VALID) {
        if (!res.success) {
          wx.hideLoading()
          bleHelper.releaseBle()
          wx.showToast({
            title: '添加密码失败，请重试',
            icon: 'none'
          })
        }
      }
    }
    bleHelper.initBle(res => {
      // 连接成功
      bleLockHelper.blueSendAddPwd(0x01, 0, "234567")

    }, res => {
      wx.hideLoading()
      wx.showToast({
        title: '连接失败，' + res,
        icon: 'none'
      })
      bleHelper.releaseBle()
    })
  }
})
